/*
 * ChangePassword.java
 *
 * Change a user's db password
 *
 * Created on July 26, 2002, 1:38 PM
 * @author  darrell
 */

package cgi.db;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;

public class ChangePassword {
	public static final String DEFAULT_USER_PREPEND = "osi$";
	
	/** Creates a new instance of ChangePassword */
	public ChangePassword() {
		
	}
	
	
	public static boolean changePassword(String username, 
											String password, 
											String newPassword, 
											String newPasswordConfirm) 
												throws NewPasswordMismatchException, InvalidUserException, SQLException, Exception {
		return changePassword(username, password, newPassword, newPasswordConfirm, OracleConnect.DEFAULT_DBNAME);
	}
	public static boolean changePassword(String username,
											String password, 
											String newPassword, 
											String newPasswordConfirm, 
											String dbname) 
												throws NewPasswordMismatchException, InvalidUserException, SQLException, Exception {
		if (newPassword == null || newPasswordConfirm == null)
			throw new NewPasswordMismatchException(true);
		if (newPassword.equals(newPasswordConfirm))
			return changePasswordDb(username, password, newPassword, dbname);
		throw new NewPasswordMismatchException(false);
	}
	
	
	protected static boolean changePasswordDb(String username, 
												String password, 
												String newPassword, 
												String dbname) 
													throws InvalidUserException, SQLException, Exception {
		if (username == null || 
			password == null || 
			newPassword == null || 
			dbname == null || 
			username.length() == 0 || 
			password.length() == 0 || 
			newPassword.length() == 0 || 
			dbname.length() == 0
			)
			throw new InvalidUserException(true);
		if (!username.startsWith("ops$"))			// PREPENDS username THE USERNAME WITH $ops
			username = "ops$"+ username;
		
		Connection con = OracleConnect.getConnection(username, password, dbname);
		Statement stmt = con.createStatement();
		stmt.execute("alter user "+ username +" identified by "+ newPassword);
		con.close();
		return true;
	}
}
